package com.cian.spring.dao;

import com.cian.spring.model.User;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import javax.sql.DataSource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author Create By Cian
 * @version 2017/11/2  21:51
 */

@Repository("jdbcUserDao")
public class UserDao implements IUserDao {

    private JdbcTemplate jdbcTemplate;


    @Resource
    public void setDataSource(DataSource dataSource) {
        this.jdbcTemplate = new JdbcTemplate(dataSource);
    }

    @Override
    public int add(User user) {

        return this.jdbcTemplate.update(
                "insert into t_user (username, password,nickname) values (?,?,?)",
                user.getUsername(), user.getPassword(), user.getNickname());

    }

    @Override
    public int update(User user) {
        return this.jdbcTemplate.update(
                "update t_user set username = ?,password=?,nickname=?  where id = ?",
                user.getUsername(), user.getPassword(), user.getNickname(), user.getId());
    }

    @Override
    public int delete(int id) {
        return this.jdbcTemplate.update("delete from t_user where id = ?", id);
    }

    @Override
    public List<User> list() {
        List<Map<String, Object>> list = this.jdbcTemplate.queryForList("select * from t_user");
        List<User> userList = new ArrayList<>();
        for (Map<String, Object> aList : list) {

//            遍历MAP的所有KEY值
//            List<String> mapKeyList = new ArrayList<>(aList.keySet());
            //遍历MAP的VALUE
            List<Object> mapValuesList = new ArrayList<>(aList.values());
            User user = new User(mapValuesList.get(0).toString(),
                                 mapValuesList.get(1).toString(),
                                 mapValuesList.get(2).toString(),
                                 Integer.parseInt(mapValuesList.get(3).toString()));
            userList.add(user);
        }

        return userList;
    }

    @Override
    public User findOne(int id) {
        List<Map<String, Object>> list = this.jdbcTemplate.queryForList("select * from t_user where id=?",id);
        User user1 = new User();
        for (Map<String, Object> aList : list) {
//            遍历MAP的所有KEY值
//            List<String> mapKeyList = new ArrayList<>(aList.keySet());
            //遍历MAP的VALUE
            List<Object> mapValuesList = new ArrayList<>(aList.values());
            User user = new User(mapValuesList.get(0).toString(),
                                 mapValuesList.get(1).toString(),
                                 mapValuesList.get(2).toString(),
                                 Integer.parseInt(mapValuesList.get(3).toString()));
            user1 = user;
        }

        return user1;
    }


}
